﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Senparc.Weixin.MP;
using NHibernate;
using ZLCMS.Data.Model;
using System.IO;
using DotNet.Common.NHibernateUtil;
using ZLCMS.Business.Util;
using ZLCMS.Business.WeixinService.CustomMessageHandler;
using NHibernate.Criterion;
using ZLCMS.Business.WeixinService.Command;
using ZLCMS.Business.WeixinService;
using System.Threading;

namespace ZLCMS.Web.Interface.weixin
{
    public partial class PlatService : UrlRewritePage
    {
        protected string Owner { get; set; }

        protected string OpenId { get; set; }

        protected void Page_Load(object sender, EventArgs e)
        {
            string signature = Request["signature"];
            string timestamp = Request["timestamp"];
            string nonce = Request["nonce"];
            string echostr = Request["echostr"];
            string account = Request["account"];
            if (string.IsNullOrEmpty(account))
            {
                WriteContent("参数错误！");
                return;
            }
            WxConfig config = null;
            using (ISession session = SessionFactoryHelper.CreateSession())
            {
                config = session.CreateQuery("from WxConfig where OwnerAccount=:code")
                    .SetParameter("code", account)
                    .UniqueResult<WxConfig>();
            }
            if (config == null)
            {
                WriteContent("参数错误！");
                return;
            }

            //messageHandler.WeixinOpenId
            if (Request.HttpMethod == "GET")
            {
                //get method - 仅在微信后台填写URL验证时触发
                if (CheckSignature.Check(signature, timestamp, nonce, config.InterfaceToken))
                {
                    WriteContent(echostr); //返回随机字符串则表示验证通过
                }
                else
                {
                    WriteContent("failed:" + signature + "," + CheckSignature.GetSignature(timestamp, nonce, config.InterfaceToken));
                }
                Response.End();
            }
            else
            {
                //post method - 当有用户想公众账号发送消息时触发,测试时要屏蔽此判断
                //if (!CheckSignature.Check(signature, timestamp, nonce, config.InterfaceToken))
                //{
                //    WriteContent("参数错误！");
                //    return;
                //}
                WxMessageRecord request = new WxMessageRecord();

                try
                {
                    //测试时可开启此记录，帮助跟踪数据
                    //                     messageHandler.RequestDocument.Save(
                    //                         Server.MapPath("~/App_Data/" + DateTime.Now.Ticks + "_Request_" +
                    //                                        messageHandler.RequestMessage.FromUserName + ".txt"));

                    var messageHandler = new CustomMessageHandler(Request.InputStream);
                    messageHandler.UserCode = account;
                    Owner = account;
                    OpenId = messageHandler.RequestMessage.FromUserName;
                    using (ISession session = DotNet.Common.NHibernateUtil.SessionFactoryHelper.CreateSession())
                    {
                        //判断是否已经有记录，如有则不需处理
                        if (messageHandler.RequestMessage.MsgId != 0)
                        {
                            object msgCount = session.CreateSQLQuery("select count(*) from Wx_Message_Record where Msg_Id=:mid")
                                   .SetParameter("mid", messageHandler.RequestMessage.MsgId)
                                   .UniqueResult();

                            if (int.Parse(msgCount.ToString()) > 0)
                            {
                                WriteContent("");
                                return;
                            }
                        }
                        request.AccountFrom = messageHandler.RequestMessage.FromUserName;
                        request.AccountTo = messageHandler.RequestMessage.ToUserName;
                        request.CreateTime = DateTime.Now;
                        request.MessageSource = messageHandler.RequestDocument.ToString();
                        request.MsgType = messageHandler.RequestMessage.MsgType.ToString();
                        request.PreviousId = 0;
                        request.RecodeType = "request";
                        request.ReturnCode = "0";
                        request.OwnerAccount = account;
                        request.MsgId = messageHandler.RequestMessage.MsgId;
                        session.Save(request);


                        //执行微信处理过程
                        messageHandler.Execute();

                        //判断用户是否已经存放在memberinfo中


                        WxMessageRecord response = new WxMessageRecord();
                        response.AccountFrom = request.AccountTo;
                        response.AccountTo = request.AccountFrom;
                        response.CreateTime = DateTime.Now;
                        response.MessageSource = messageHandler.ResponseDocument == null ? "null" : messageHandler.ResponseDocument.ToString();
                        response.MsgType = request.MsgType;
                        response.PreviousId = request.Id;
                        response.RecodeType = "response";
                        response.ReturnCode = "0";
                        response.OwnerAccount = account;
                        session.Save(response);

                        session.Flush();
                        string memberName = session.CreateSQLQuery("select member_name from member_info where WX_OPEN_ID=:oid")
                            .SetParameter("oid", messageHandler.RequestMessage.FromUserName).UniqueResult<string>();

                       
                    }

                    WriteContent(messageHandler.ResponseDocument == null ? "" : messageHandler.ResponseDocument.ToString());
                    return;
                }
                catch (Exception ex)
                {
                    CMSKits.WriteLog("wxsrv", ex.Message, ex.StackTrace);
                    WriteContent("");
                }
                finally
                {
                    Response.End();
                }
            }
        }

        private void WriteContent(string str)
        {
            Response.Output.Write(str);
        }

    }
}